package com.zx.mes.hyl.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zx.mes.hyl.entity.Store;
import com.zx.mes.hyl.mapper.StoreMapper;
import com.zx.mes.hyl.rocket.mq.consume.IConsumeMessage;
import com.zx.mes.hyl.utils.FastJsonConvertUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 真正执行扣库存操作
 * GT 就是 GREATER THAN大于
 * LT 就是 LESS THAN小于
 * GE 就是 GREATER THAN OR EQUAL 大于等于
 * LE 就是 LESS THAN OR EQUAL 小于等于
 *
 * @author 华云龙
 * @date 2018-12-11
 */
@Log4j2
@Component
public class ConsumeMessageImpl implements IConsumeMessage {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private StoreMapper storeMapper;

    @Override
    public boolean consumeMessage(List<MessageExt> msg, ConsumeConcurrentlyContext context) {

        boolean flag = true;

        try {
            /// 提取消息并进行转换
            MessageExt messageExt = msg.get(0);

            log.debug(messageExt);

            Store store = FastJsonConvertUtil.convertJSONToObject(new String(messageExt.getBody()), Store.class);
            /// 扣库存时过滤掉重复操作,虽然在创建订单的时候也会做,但防止那万分之一的神操作(使用乐观锁)
            Integer storeCount = store.getStoreCount();

            /// 做乐观锁使用
            Integer version = store.getVersion();

            /// 下面两个确定唯一一笔记录
            String supplierId = store.getSupplierId();
            String goodsId = store.getGoodsId();

            /// 执行sql操作
            Store s = new Store();
            s.setUpdateTime(LocalDateTime.now())
                    .setStoreCount(storeCount - 1)
                    .setVersion(version + 1);
            int update = storeMapper.update(s, new QueryWrapper<Store>()
                    .lambda()
                    .eq(Store::getGoodsId, goodsId)
                    .eq(Store::getSupplierId, supplierId)
                    .eq(Store::getVersion, version)
                    .gt(Store::getStoreCount, 0));
            /// 只有更新的是一条记录,才是对的,其它的都是异常情况,但是默认的是成功的,需要人工处理
            if (update == 1) {

            } else {
                flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
